var core = require('core');
var isUser = require('./isUser');
var wechat = core.wechat;
var wapi = wechat.api;
var wconfig = wechat.config;
var accessToken = wechat.getAccessToken;

var reg = function(data, callback){
    var param = {
        access_token : wconfig.accessToken,
        openid : data.openid,
        lang : "zh_CN"
    };
    wapi.list.user.getUser(param, function(err, user){
        try {
            if(user.errcode){
                var err = new Error(user.errmsg);
                err.code = user.errcode;
                throw err;
            }

            user.tagid_list = user.tagid_list.join(",");
            user.name = user.nickname;

            core.api('user/reg', user, function(err, doc){
                if(doc.code)
                    throw new Error(doc.msg);

                if(callback && typeof callback === 'function') callback(doc);

            });

        } catch (e) {
            console.error(e.message);
            if(e.code == 40001){
                accessToken(function(){
                    reg(data, callback);
                });
            }
            else if(callback && typeof callback === 'function') callback(e);
        }

    });
};

module.exports = reg;
